import sys
import pylab as plt
import os
from params import *

def median(x,c):
    for x_v,c_v in zip(x,c):
        if c_v>=0.5:
            return x_v
    return None

tracefile = os.path.join(WORKDIR, 'gowalla', 'data', 'checkins', 'monthly',
    'gowalla_all_checkins_2010-08-05.txt')

place_per_user = {}
user_per_place = {}
checkins_per_user = {}
checkins_per_place = {}
for line in open(tracefile):
    user,place,num = map(int,line.split(','))

    if not user in place_per_user:
        place_per_user[user] = set()
    place_per_user[user].add(place)
    if not place in user_per_place:
        user_per_place[place] = set()
    user_per_place[place].add(user)

    if not user in checkins_per_user:
        checkins_per_user[user] = 0
    checkins_per_user[user] += num

    if not place in checkins_per_place:
        checkins_per_place[place] = 0
    checkins_per_place[place] += num

def plot_cdf(data,namefile,f, xlbl):
    pdf = {}
    for v in data:
        num_v = f(data[v])
        if not num_v in pdf:
            pdf[num_v] = 0
        pdf[num_v] += 1

    x = sorted(pdf)
    y = [pdf[k] for k in x]
    c = [y[0]]
    for i in range(1,len(y)):
        t = c[i-1] + y[i]
        c.append(t)
    tot = c[-1]
    c = map(lambda x: 1.0*x/tot, c)
    c = map(lambda x: 1-x, c)
    print namefile
    print c[:5]

    plt.figure()
    plt.clf()
    plt.axes(FIG_AXES2)
    #plt.semilogx(x,c,'k.')
    plt.loglog(x,c,'ko', mfc='None')
    plt.xlabel(xlbl)
    plt.ylabel('CCDF')
    plt.grid(True)
    [x1,x2,y1,y2] = plt.axis()
    plt.axis([x1,x2,0,1])
    plt.savefig(namefile)
    plt.close()


#plot_cdf(user_per_place,'dist_user_place_%s.pdf'%date,len)
plot_cdf(place_per_user,'gowalla_dist_place_per_user.pdf',len, 'Places')
#plot_cdf(checkins_per_place,'gowalla_dist_checkin_per_place.pdf', lambda x: x)
plot_cdf(checkins_per_user,'gowalla_dist_checkin_per_user.pdf',lambda x:x,
    'Check-ins')
 
